﻿#pragma once
#include <bits/stdc++.h>
#include "tree.h"
#include "list.h"

using namespace std;

/*  =================== 2024年2月28日10点00分 ===================
*
*   =================== hot100【难】：链表归并排序  ===================
* 
*   最适合链表的排序算法是归并排序，插入排序【leetcode_147】的时间复杂度是 O(n2)，其中 n 是链表的长度
* 
*/

// 合并2个有序链表
#include "leetcode_21/Solution.h"

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (!head || !head->next) return head;

        // 快慢指针找到中点
        ListNode* slow = head, * fast = head, * pre = nullptr;
        while (fast && fast->next) 
        {
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        pre->next = nullptr; // 分割链表

        // 递归分割
        ListNode* l1 = sortList(head);
        ListNode* l2 = sortList(slow);

        // 合并排序后的链表
        return merge(l1, l2);
    }

private:
    ListNode* merge(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode(0);
        ListNode* cur = dummy;
        while (l1 && l2) 
        {
            if (l1->val < l2->val) 
            {
                cur->next = l1;
                l1 = l1->next;
            }
            else 
            {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        cur->next = l1 ? l1 : l2;
        return dummy->next;
    }
};